var left_viewer = $('#left_viewer');
var persons=$('#persons');
// 更新UI，根据json返回的结果。
var timer = null;
var timeout = 0;
//设置leftview的淡出淡入效果动画时间长短
var fadeIn_Out = 3;
//设置leftview显示的持续时间长短
var left_view_toast_time = 10000;//10s*10
var personlist = new Map();
//预删除队列
var predellist=new Map();
//正常自动删除时间是60s,但是当行人退出屏幕后，应该在10s内删除。
var MAX_PEOPLE_TTL=36;//12*5sec

if (window.Streamedian) {
    let errHandler = function (err) {
        alert(err.message);
    };

    let infHandler = function (inf) {
        let sourcesNode = document.getElementById("sourcesNode");
        let clients = inf.clients;
        sourcesNode.innerHTML = "";
        for (let client in clients) {
            clients[client].forEach((sources) => {
                let nodeButton = document.createElement("button");
                nodeButton.setAttribute('data', sources.url + ' ' + client);
                nodeButton.appendChild(document.createTextNode(sources.description));
                nodeButton.onclick = (event) => {
                    setPlayerSource(event.target.getAttribute('data'));
                };
                sourcesNode.appendChild(nodeButton);
            });
        };
    };

    var playerOptions = {
        socket: "ws://localhost:8088/ws/", redirectNativeMediaErrors: true,
        bufferDuration: 30,
        errorHandler: errHandler,
        infoHandler: infHandler
    };
    var player = Streamedian.player('test_video', playerOptions);
}

//当视频中识别到认识的人时，调用此函数将其信息显示到屏幕左侧的框中。
function addKnown(id, name, user_id) {
    persons.append('<div class="person known" data-id="' + id + '" >\
                                    <div style="text-align:center"><img src="/static/img/pic1/' + user_id + '.jpg?random='+Math.random()+'" width="100%" height="160px" /></div>\
                                    <div style="text-align:center;background-color:white;font-weight: bold;"><span>'+id+'&ensp;</span><span>' + name + '</span></div>\
                                </div>');
    persons.scrollTop(persons.prop("scrollHeight"));
    persons.css('display', 'block');
}

//当视频中识别到不认识的人时，调用此函数将其信息显示到屏幕左侧的框中，用红色框显著提示。
function addUnknown(id, img) {
    persons.append('<div class="person unknown" data-id="' + id + '" >\
                            <div style="text-align:center"><img src="/static/img/' + img + '" width="100%" height="160px" /></div>\
                                    <div style="text-align:center;background-color:white;font-weight: bold;"><span>Unknown</span></div>\
                                </div>');
    persons.scrollTop(persons.prop("scrollHeight"));
    persons.css('display', 'block');
}

//模拟在视频中检测到了认识的人。
//        $('#addperknown').click(function () {
//            addKnown('1001','lining', '1.JPG');
//            if ($('#left_viewer').css('display') == 'none') {
//                $('#left_viewer').fadeIn(1000);
//            if ($('#persons').children.length * 180 > $('#persons').height()) {
//                $('.scrollbot-scrollbar-holder').css('display', 'block');
//            if (timer == null) {
//                start_timer();
//        );
//        //模拟在视频中检测到了不认识的人。
//        $('#addperunknown').click(function () {
//            addUnknown('38000','1.JPG');
//            if ($('#left_viewer').css('display') == 'none') {
//                $('#left_viewer').fadeIn(5000);
//            if ($('#persons').children.length * 180 > $('#persons').height()) {
//                $('.scrollbot-scrollbar-holder').css('display', 'block');
//            if (timer == null) {
//                start_timer();
//        );

function addUnKnownPerson(id, img) {
    addUnknown(id, img);
    if (left_viewer.css('display') == 'none')
        left_viewer.fadeIn(fadeIn_Out);
    if (persons.children.length * 180 > persons.height())
        $('.scrollbot-scrollbar-holder').css('display', 'block');
}

function addKnownPerson(id, name, user_Id) {
    addKnown(id, name, user_Id);
    if (left_viewer.css('display') == 'none')
        left_viewer.fadeIn(fadeIn_Out);
    if (persons.children.length * 180 > persons.height())
        $('.scrollbot-scrollbar-holder').css('display', 'block');
}

function addBoxKnownPersonWithGA(trk_id,name,user_Id,bbox,gender,age){
    $('#people_boxes_container').append('<div class="people_boxes known" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"><div style="background-color:green;border-radius:50px;text-align:center;font-weight:bold;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+name+'&nbsp;'+gender+'&nbsp;'+age+'</div></div>');
}

function addBoxUnKnownPersonWithGA(trk_id,bbox,gender,age){
    $('#people_boxes_container').append('<div class="people_boxes unknown" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"><div style="background-color:red;border-radius:50px;text-align:center;font-weight:bold;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+gender+'&nbsp;'+age+'</div></div>');
}

function addBoxKnownPersonWithoutGA(trk_id,name,user_Id,bbox){
    $('#people_boxes_container').append('<div class="people_boxes known" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"><div style="background-color:green;border-radius:50px;text-align:center;font-weight:bold;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+name+'</div></div>');
}

function addBoxUnKnownPersonWithoutGA(trk_id,bbox){
    $('#people_boxes_container').append('<div class="people_boxes unknown" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"><div style="background-color:red;border-radius:50px;text-align:center;font-weight:bold;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">Unknown</div></div>');
}

function start_timer() {
    timeout = 0;
    timer = setInterval(function () {
        timeout += 1;
        if (timeout > 10) {
            left_viewer.fadeOut(fadeIn_Out);
            clearInterval(timer);
            timer = null;
            timeout = 0;
        }
    }, left_view_toast_time);
}

left_viewer.hover(function () {
    clearInterval(timer);
}, function () {
    start_timer();
});

//region +自定义滚动条初始化
//自定义滚动条，对自定义滚动条进行初始化，监听滚动条的状态；
customscroll = new scrollbot(".custom-scroll-4", 10).setStyle({
    "background": "#202020",
    "z-index": "2",
    "border-radius": "50%",
    "height": "10px"
}, {
    "background": "rgba(0,0,0,0)"
});
let psuedo = document.createElement("div");
psuedo.style.cssText = "height:100%;width:2px;left:4px;background:#808080;position:absolute;z-index:1";
customscroll.scrollBarHolder.appendChild(psuedo);
document.onreadystatechange = function () {
    customscroll.refresh();
};
persons=$('#persons');
//endregion

//启动截图；每隔一定的时间截一次图，然后上传到服务器进行识别。
function ResolveResult(data) {
        //如果返回errorcode=0，则说明请求识别正常，可以用来渲染页面了。
        data=JSON.parse(data.data);
        if (data["errorcode"] == 0) {
            $('#people_boxes_container').empty();
            result = data["result"];
            show_ga=data['show_ga'];
            for (i = 0; i < result.length; i++) {
                per = result[i];
                //执行显示操作。对于有没有在数据库中进行区别对待。
                pId = per["user_Id"];
                name=per["name"];
                trk_Id=per["id"];
                bbox = per["bbox"];
                if (show_ga){
                    age=per['age'];
                    gender=per['gender'];
                    bbox[1]=bbox[1]-80;
                }

                //如果在不在最近缓存列表中，重新显示，更新
                if (!personlist.has(pId)){
                    //更新；
                    if (per["IsUnKnown"] == 0) {
                    //渲染认识的
                    //当要显示的人已经在当前屏幕显示列表中时，需要先从列表删除。
                    addKnownPerson(pId, name, pId);
                        if(show_ga) {
                        //$('#people_boxes_container').append('<div class="people_boxes known" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"></div>');
                            addBoxKnownPersonWithGA(trk_Id, name, pId, bbox, gender == 1 ? '男' : gender == 0 ? '女' : '', gender==null? '识别中':age);
                        }
                        else{
                            addBoxKnownPersonWithoutGA(trk_Id, name, pId, bbox);
                        }
                    }
                    else {
                    //渲染不认识的
                    //addUnKnownPerson(pId, '123.jpg');
                    //$('#people_boxes_container').append('<div class="people_boxes unknown" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"></div>');
                        if(show_ga) {
                            addBoxUnKnownPersonWithGA(trk_Id, bbox, gender == 1 ? '男' : gender == 0 ? '女' : '', gender == null ? '识别中' : age);
                        }
                        else{
                            addBoxUnKnownPersonWithoutGA(trk_Id, bbox);
                        }
                    }
                }
                //否则，只是重新显示出左侧悬浮窗口，当前只是在认识的人显示
                else{
                    //不更新；
                    if (per["IsUnKnown"] == 0) {
                        if (left_viewer.css('display') == 'none')
                            left_viewer.fadeIn(fadeIn_Out);
                    //渲染认识的
                        if(show_ga) {
                            //$('#people_boxes_container').append('<div class="people_boxes known" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"></div>');
                            addBoxKnownPersonWithGA(trk_Id, name, pId, bbox, gender == 1 ? '男' : gender == 0 ? '女' : '', gender == null? '识别中' : age);
                        }
                        else{
                            addBoxKnownPersonWithoutGA(trk_Id, name, pId, bbox);
                        }
                    }
                    else {
                    //渲染不认识的
                    //$('#people_boxes_container').append('<div class="people_boxes unknown" style="left:' + (bbox[0]) + 'px;top:' + (bbox[1]) + 'px;width:' + (bbox[2]) + 'px;height:' + (bbox[3]) + 'px;"></div>');
                        if(show_ga) {
                            addBoxUnKnownPersonWithGA(trk_Id, bbox, gender == 1 ? '男' : gender == 0 ? '女' : '', gender == null ? '识别中' : age);
                        }
                        else{
                            addBoxUnKnownPersonWithoutGA(trk_Id, bbox);
                        }
                    }
                }
                personlist.set(pId,MAX_PEOPLE_TTL);
                //setTimeout(function(){$('#people_boxes_container').empty();},500)
            }
            if(result.length>0){
                if (timer!=null){
                    timeout=0;
                }
                else{
                    start_timer();
                }
            }
            users_id=data["users_id"]
            //扫描一遍personlist,把当前不存在的用户标出来，时间减去一些。
            for(var item of personlist){
                if(!(item[0] in users_id)){
                    personlist.set(item[0],item[1]-0.006);
                }
            }
        }
    }
ws1=new WebSocket("ws://127.0.0.1:8100");
ws1.onmessage=ResolveResult;
ws1.onopen=function(){
    //客户端在建立连接后向服务器发送监控设备的Id；然后服务器端开启线程，获取对应的监控设备的视频帧
    ws1.send('1');
};
ws1.onclose=function(){
    console.log('服务器已关闭');
    //服务器关闭后自动重新建立websocket连接；
    ws1=new WebSocket("ws://127.0.0.1:8100");
};
ws1.onerror=function(){
    console.log('服务器出现错误！');
};

//启动定时器任务，用来检查界面显示的框有没有过期，如果过期，就清理掉。
setInterval(function(){
    for(let [key,value] of personlist.entries()){
        personlist.set(key,value-1);
        if (value<=0){
            personlist.delete(key);
            //从界面中删掉
            $(document.querySelectorAll('[data-id="' + key + '"]')).remove();
        }
    }
},5000);


